//
//  AIMakeupViewController.swift
//  月升
//
//  Created by 拉利法 on 2024/7/11.
//  AI化妆

import UIKit

class AIMakeupViewController: QIBaseViewController {
    
    /// 预览提
    var previewImg = UIImage()
    /// 原图
    var originalImg = UIImage()
    /// 原图在本地服务器地址
    var originalImgUrl = ""
    /// 预览图片地址
    var previewImgUrl = ""
    var event_name = ""
    var selectedOptions = ""
    var Local_Save_Path = ""
    /// 腮红(从收藏列表传过来)
    var powder_blusher = [String: Any]()
    /// 眼影(从收藏列表传过来)
    var eye_shadow = [String: Any]()
    /// 口红(从收藏列表传过来)
    var lipstick = [String: Any]()
    /// 视频模型
    var videoModel = QIBeautyRecommenListModel()
    private var imgPreviewView = UIImageView()
    private var dataArr = [QIFacialFeaturesModel]()
    /// 更新试装之后的图片
    private var changeImgUrl = ""
    private var collectionBtn = UIButton()
    private var collectID = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "AI化妆"
        dataArr = [
            QIFacialFeaturesModel(title: "眼影", value: "无"),
            QIFacialFeaturesModel(title: "腮红", value: "无"),
            QIFacialFeaturesModel(title: "口红", value: "无")
        ]
        
        if eye_shadow.keys.count > 0 {
            modifyModel(index: 0, dict: eye_shadow)
        }
        if powder_blusher.keys.count > 0 {
            modifyModel(index: 1, dict: powder_blusher)
        }
        if lipstick.keys.count > 0 {
            modifyModel(index: 2, dict: lipstick)
        }

        addUI()
    }
    

    
    private func addUI() {
        showGradientColor()
        
        rightBtn.setImage(UIImage(named: "更多三点"), for: .normal)
        rightBtn.addTarget(self, action: #selector(moreBtnClick), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        myCategoryView.frame = CGRect(x: SCREEN_WIDTH / 2 - 65, y: NAV_HEIGHT, width: 130, height: 34)
        view.addSubview(myCategoryView)
        
        imgPreviewView = UIImageView().then {
            $0.frame = CGRect(x: 15, y: myCategoryView.bottom + 10, width: SCREEN_WIDTH - 30, height: 410)
            $0.image = previewImg
            $0.tag = 11
            $0.contentMode = .scaleAspectFill
            $0.clipsToBounds = true
            $0.addRoundedCorners(withRadius: 10)
        }
        if previewImgUrl.count > 0 {
            imgPreviewView.kf.setImage(with: URL(string: previewImgUrl), placeholder: previewImg)
        }
        view.addSubview(imgPreviewView)
        
        let footView = UIView()
        footView.frame = CGRect(x: 0, y: imgPreviewView.bottom + 10, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - imgPreviewView.bottom - 10)
        footView.backgroundColor = .white
        footView.addRoundedCorners(withRadius: 10, byRoundingCorners: [.topLeft, .topRight])
        view.addSubview(footView)
        
        let titleL = UILabel().then({
            $0.frame = CGRect(x: 0, y: 13, width: 100, height: 22)
            $0.centerX = footView.centerX
            $0.text = "偏好选择"
            $0.textAlignment = .center
            $0.textColor = Color333333
            $0.font = FONTBOLD(ofSize: 16)
        })
        footView.addSubview(titleL)
        
        collectionBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH - 45, y: 0, width: 29, height: 29)
            $0.centerY = titleL.centerY
            $0.isSelected = self.videoModel.isCollect
            $0.setImage(UIImage(named: "未收藏_试妆"), for: .normal)
            $0.setImage(UIImage(named: "已收藏_试妆"), for: .selected)
            $0.addTarget(self, action: #selector(collectionBtnClick(btn:)), for: .touchUpInside)
        }
        footView.addSubview(collectionBtn)
        
        collectionView.frame = CGRect(x: 10, y: titleL.bottom + 10, width: SCREEN_WIDTH - 20, height: 120)
        footView.addSubview(collectionView)
        
        
        let refreshBtn = UIButton().then {
            $0.frame = CGRect(x: 0, y: 190, width: 114, height: 36)
            $0.centerX = footView.centerX
            $0.backgroundColor = ColorWithStr("#FFD5DA")
            $0.titleLabel?.font = FONT(ofSize: 16)
            $0.setTitle("更新试妆", for: .normal)
            $0.setTitleColor(MainColor, for: .normal)
            $0.addRoundedCorners(withRadius: 18)
            $0.addTarget(self, action: #selector(refreshBtnClick), for: .touchUpInside)
        }
        footView.addSubview(refreshBtn)
    }
    
    private func modifyModel(index: Int, dict: [String: Any]) {
        let rgbColorStr = "\(dict["rgbColorStr"] ?? "")"
        let rgbColorArr = rgbColorStr.components(separatedBy: ",")
        dataArr[index].colorName = "\(dict["colorName"] ?? "")"
        let r = Double("\(rgbColorArr[0])") ?? 0.0
        let g = Double("\(rgbColorArr[1])") ?? 0.0
        let b = Double("\(rgbColorArr[2])") ?? 0.0
        dataArr[index].value = "\(dict["shape"] ?? "")"
        dataArr[index].bgColor = UIColor(red: CGFloat(r / 255.0), green: CGFloat(g / 255.0), blue: CGFloat(b / 255.0), alpha: 1)
    }
    
    /// 收藏试妆
    @objc private func collectionBtnClick(btn: UIButton) {
        if videoModel.isCollect {
            QINetworkManager.requestJson(urlStr: "/Skin/cancel_collect", parameters: ["collect_id": videoModel.id]) { json in
                print(json)
                btn.isSelected = false
                self.videoModel.isCollect = false
            }
        } else {
            guard changeImgUrl.count > 0 else {
                ShowHUD(str: "请更新试妆后再收藏")
                return
            }
            guard imgPreviewView.image != originalImg else {
                ShowHUD(str: "不能收藏原图")
                return
            }
            
            let param = [
                "event_name": event_name,
                "local_save_path": Local_Save_Path,
                "video_id": videoModel.vModel.id,
                "image": changeImgUrl,
                "eye_shadow": getColorInfo(model: dataArr[0]),
                "powder_blusher": getColorInfo(model: dataArr[1]),
                "lipstick": getColorInfo(model: dataArr[2]),
                "original_drawing": originalImgUrl,
                "name": videoModel.title
            ]
            QINetworkManager.requestJson(urlStr: "/Skin/collect_makeup", parameters: param) { json in
                print(json)
                self.videoModel.id = json.stringValue
                btn.isSelected = true
                self.videoModel.isCollect = true
            }
        }
    }
    
    
    private func getColorInfo(model: QIFacialFeaturesModel) -> String {
        let dict = [
            "colorName": model.colorName,
            "rgbColorStr": model.rgbColorStr,
            "shape": model.value
        ]
        return dictionaryToJsonString(dictionary: dict)
    }
    
    
    /// 更新试装
    @objc private func refreshBtnClick() {
        let rgbColorArr = dataArr.map({$0.rgbColorStr})
        let url = "http://124.222.206.164:9100/develop_color_change"
        let selectedOptions = rgbColorArr.joined(separator: ",")
        guard selectedOptions.count > 8 else {
            ShowHUD(str: "请更新偏好选择")
            return
        }
        
        HUD.flash(.labeledProgress(title: "", subtitle: "数据获取中..."), delay: 60)
        let param = [
            "event_name": event_name,
            "selectedOptions": "\(selectedOptions),0",     //最后一个双眼皮,默认不加
            "Local_Save_Path": Local_Save_Path
        ]
        QINetworkManager.requestJson(urlStr: url, parameters: param, isJson: true) { json in
            print(json)
            HUD.hide()
            let urlStr = json["Cos_Save_Path_Color_Change"].stringValue
            self.imgPreviewView.kf.setImage(with: URL(string: "\(DetectionIMAGE_URL1)\(urlStr)"), placeholder: self.originalImg, options: [.forceRefresh])
            self.previewImgUrl = "\(DetectionIMAGE_URL1)\(urlStr)"
            self.changeImgUrl = urlStr
        }
    }
    //
    
    @objc private func moreBtnClick() {
        let alertCtl = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alertCtl.addAction(UIAlertAction(title: "更新风格", style: .default, handler: { (_) in
            self.navigationController?.viewControllers.forEach({ ctl in
                if ctl.classForCoder == FilterCriteriaVideoListViewController.classForCoder() {
                    self.navigationController?.popToViewController(ctl, animated: true)
                }
            })
        }))
        alertCtl.addAction(UIAlertAction(title: "清空偏好", style: .default, handler: { (_) in
            self.dataArr = [
                QIFacialFeaturesModel(title: "眼影", value: "无", bgColor: .white),
                QIFacialFeaturesModel(title: "腮红", value: "无", bgColor: .white),
                QIFacialFeaturesModel(title: "口红", value: "无", bgColor: .white)
            ]
            self.collectionView.reloadData()
        }))
        alertCtl.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            
        }))
        self.present(alertCtl, animated: true)
    }
    
    func dictionaryToJsonString(dictionary: [String: Any]) -> String {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: [])
            let jsonString = String(data: jsonData, encoding: .utf8)
            return jsonString ?? ""
        } catch {
            print("Error converting dictionary to JSON string: \(error)")
            return ""
        }
    }

    lazy var myCategoryView: JXCategoryTitleView = {
        let lineView = JXCategoryIndicatorBackgroundView()
        lineView.indicatorHeight = 34
        lineView.indicatorColor = MainColor
        
        let myCategoryView = JXCategoryTitleView()
        myCategoryView.backgroundColor = .white
        myCategoryView.delegate = self
        myCategoryView.titleColor = Color999999
        myCategoryView.titleSelectedColor = .white
        myCategoryView.titleFont = FONT(ofSize: 14)
        myCategoryView.titleSelectedFont = FONT(ofSize: 14)
        myCategoryView.titles = ["AI化妆", "原图"]
        myCategoryView.cellWidth = 65
        myCategoryView.cellSpacing = 0
        myCategoryView.indicators = [lineView]
        myCategoryView.defaultSelectedIndex = 0
        myCategoryView.addRoundedCorners(withRadius: 17)
        return myCategoryView
    }()
    
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 1
        flowLayout.minimumInteritemSpacing = 1
        flowLayout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.register(FilterCriteriaViewCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        
        return collectionView
    }()
}

extension AIMakeupViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let cellW = (SCREEN_WIDTH - 55) / 3
        return CGSize(width: cellW, height: 110)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! FilterCriteriaViewCell
        cell.backgroundColor = UIColor.white
        cell.addProjection(withShadowOpacity: 0.1)
        if dataArr.count > indexPath.row {
            var model = dataArr[indexPath.row]
            model.type = "偏好选择"
            cell.model = model
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vv = MakeupColorSelectttView(frame: CGRect(x: 65, y: imgPreviewView.top + 50, width: SCREEN_WIDTH - 130, height: indexPath.row == 2 ? 270 : 340))
        if indexPath.row == 0 {
            vv.typeStr = "眼影"
        } else if indexPath.row == 1 {
            vv.typeStr = "腮红"
        } else if indexPath.row == 2 {
            vv.typeStr = "口红"
        }
        vv.selectColorBlock = { tuple in
            self.dataArr[indexPath.row].colorName = tuple.colorName
            self.dataArr[indexPath.row].value = tuple.colorLab
            self.dataArr[indexPath.row].bgColor = tuple.selectColor
            self.dataArr[indexPath.row].rgbColorStr = tuple.rgbColorStr
            self.dataArr[indexPath.row].selectTypeIndex = tuple.selectTypeIndex
            collectionView.reloadData()
            self.collectionBtn.isSelected = false
        }
        QINPopUpTool.sharedInstance().popUp(with: vv, withAnimation: .none, withCanTapBgCancel: false, closeBefore: .close, bgColor: .clear)
    }
    
}

extension AIMakeupViewController: JXCategoryViewDelegate {
    
    func categoryView(_ categoryView: JXCategoryBaseView!, didClickSelectedItemAt index: Int) {
        print(index)
        if index == 0 {
            if previewImg.size.width == 0 || previewImg.size.height == 0 {
                imgPreviewView.kf.setImage(with: URL(string: previewImgUrl))
            } else {
                imgPreviewView.image = previewImg
            }
            
        } else {
            imgPreviewView.kf.setImage(with: URL(string: originalImgUrl))
        }
    }
    
    func categoryView(_ categoryView: JXCategoryBaseView!, didScrollSelectedItemAt index: Int) {
        print(index)
        if index == 0 {
            if previewImg.size.width == 0 || previewImg.size.height == 0 {
                imgPreviewView.kf.setImage(with: URL(string: previewImgUrl))
            } else {
                imgPreviewView.image = previewImg
            }
        } else {
            imgPreviewView.kf.setImage(with: URL(string: originalImgUrl))
        }
    }
}
